package com.drcoffee.drcoffeemall.filter;

import com.drcoffee.drcoffeemall.service.BsUserService;
import com.drcoffee.drcoffeemall.service.impl.BsUserServiceImpl;
import com.drcoffee.drcoffeemall.util.SpringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class TokenFilter extends OncePerRequestFilter {

    //    @Autowired
    private BsUserService bsUserService;

    private static final List<String> excludedPaths = Arrays.asList(
            "/bs_user/login",
            "/bs_user/verifyAccount",
            "/bs_user/removeToken",
            "/bs_user/verifyToken",
            "/file/",
            "/edit/partImageProcessing"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        String private_ip = request.getRemoteAddr();
        System.out.println("请求路径：" + requestURI);
        System.out.println("请求方式：" + request.getMethod());
        System.out.println("公网IP：" + xForwardedFor);
        System.out.println("客户端IP：" + private_ip);
        String ip = null;
        if (xForwardedFor != null) {
            String[] ips = xForwardedFor.split(",");
            ip = ips[0].trim();
        }
        if (isExcludedPath(requestURI) || isOptionsMethod(request) || isLocalRequest(request)) {
            filterChain.doFilter(request, response);
        } else {
            String token = request.getHeader("Token");
            if (isValidToken(token)) {
                // Token有效，继续处理请求
                System.out.println("====================================== 有效 ======================================");
                bsUserService.renewalToken(token);
                filterChain.doFilter(request, response);
            } else {
                System.out.println("====================================== 无效 ======================================");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
    }

    private boolean isExcludedPath(String path) {
        return excludedPaths.stream().anyMatch(path::endsWith);
    }

    private boolean isOptionsMethod(HttpServletRequest request) {
        return "OPTIONS".equals(request.getMethod());
    }

    private boolean isLocalRequest(HttpServletRequest request) {
        return "127.0.0.1".equals(request.getRemoteHost());
    }

    private boolean isValidToken(String token) {
        if (bsUserService == null) {
            this.bsUserService = SpringUtils.getBean(BsUserServiceImpl.class);
        }
        return bsUserService.verifyToken(token);
    }
}
